<template>
  <div class="editWedding">
    <h1 v-if="id">编辑酒店案例</h1>
    <h1 v-else>添加酒店案例</h1>
    <el-form ref="formline" :rules="rules" class="box" label-width="80px" :model="formline">
      <el-form-item label="轮播图:" class="topimg" prop="imagesData">
        <template slot-scope="scope">
          <form class="banner_loade" enctype="multipart/form-data">
            <el-button class="upload" type="primary ">
              添加多张图片
              <input class="file" type="file" name="file" @change="uploadImg($event)" />
            </el-button>
            <div class="loade_img" :class="{hide:formline.imagesData!=''}">
              <div style="position: relative;" v-for="(img,index) in formline.imagesData" :key="index">
                <img class="img_auto" :src="img" alt />
                <i class="el-icon-error icon" @click="deleteImg(index)"></i>
              </div>
            </div>
          </form>
        </template>
      </el-form-item>
      <el-form-item label="酒店名:" label-width="120px" prop="hotelname">
        <el-input v-model="formline.hotelname"></el-input>
      </el-form-item>
      <el-form-item label="标签:" label-width="120px" prop="dynamicTags">
        <el-tag :key="tag" v-for="(tag,index) in formline.dynamicTags" closable :disable-transitions="false" @close="handleClose(index)">{{tag}}</el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
          @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"></el-input>
        <el-button class="button-new-tag" size="small" v-if="show" @click="showInput()">+标签</el-button>
      </el-form-item>
      <el-form-item label="容纳:" label-width="120px" prop="contain">
        <el-input v-model="formline.contain"></el-input>
      </el-form-item>
      <el-form-item label="地址:" label-width="120px" prop="address">
        <el-input v-model="formline.address"></el-input>
      </el-form-item>
      <el-form-item label="起订价:" label-width="120px" prop="price">
        <el-input v-model="formline.price"></el-input>
      </el-form-item>
      <el-form-item label="图文介绍:" label-width="120px">
        <div id="editorElem" style="width:55vw"></div>
      </el-form-item>
    </el-form>

    <!-- 宴会厅 -->
    <div class="banner">
      <div class="banner-header">
        <span>宴会厅</span>
        <div class="push-banner">
          <i class="el-icon-circle-plus" @click="push_case()"></i>
          <span>添加宴会厅</span>
        </div>
      </div>
      <!-- 表格主体 -->
      <div class="banner-table item-table">
        <el-table :data="bollroom" border>
          <el-table-column fixed prop="num" label="排序" min-width="30px" align="center"></el-table-column>
          <el-table-column label="图片" width="220" align="center">
            <template slot-scope="scope">
              <form class="banner_loade" enctype="multipart/form-data">
                <el-button class="upload" size="mini" type="primary ">
                  上传图片
                  <input class="file" type="file" name="file" :id="scope.$index" @change="bollroomImg($event,scope.$index)" />
                </el-button>
                <div class="loade_img">
                  <img class="img_auto" :src="bollroom[scope.$index].picture" alt />
                </div>
              </form>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="宴会厅名" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="bollroom[scope.$index].changes">{{bollroom[scope.$index].name}}</span>
                <el-input v-if="!bollroom[scope.$index].changes" placeholder="请填写宴会厅名" v-model="bollroom[scope.$index].name"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="floor" label="楼层" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="bollroom[scope.$index].changes">{{bollroom[scope.$index].floor}}</span>
                <el-input v-if="!bollroom[scope.$index].changes" placeholder="请填写楼层" v-model="bollroom[scope.$index].floor"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="height" label="厅高" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="bollroom[scope.$index].changes">{{bollroom[scope.$index].height}}</span>
                <el-input v-if="!bollroom[scope.$index].changes" placeholder="请填写厅高" v-model="bollroom[scope.$index].height"></el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="pillar" label="柱子" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="bollroom[scope.$index].changes">{{bollroom[scope.$index].pillar}}</span>
                <el-input v-if="!bollroom[scope.$index].changes" placeholder="柱子" v-model="bollroom[scope.$index].pillar"></el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="table" label="桌数" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="bollroom[scope.$index].changes">{{bollroom[scope.$index].table}}</span>
                <el-input v-if="!bollroom[scope.$index].changes" placeholder="请填写桌数" v-model="bollroom[scope.$index].table"></el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="pricing" label="起订价" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="bollroom[scope.$index].changes">{{bollroom[scope.$index].pricing}}</span>
                <el-input v-if="!bollroom[scope.$index].changes" placeholder="请填写起订价" v-model="bollroom[scope.$index].pricing"></el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="250" align="center">
            <template slot-scope="scope">
              <el-button @click="editHotel(scope.$index)" type="primary" size="mini">编辑</el-button>
              <el-button @click="cancelBollroom(scope.$index,scope.row)" type="primary" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 婚宴菜单 -->
    <div class="banner">
      <div class="banner-header">
        <span>婚宴菜单</span>
        <div class="push-banner">
          <i class="el-icon-circle-plus" @click="push_Menu()"></i>
          <span>婚宴菜单</span>
        </div>
      </div>
      <!-- 表格主体 -->
      <div class="banner-table item-table">
        <el-table :data="menuData" border>
          <el-table-column fixed prop="num" label="排序" border align="center"></el-table-column>
          <el-table-column prop="dishname" label="菜单名" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="menuData[scope.$index].changes">{{menuData[scope.$index].dishname}}</span>
                <el-input v-if="!menuData[scope.$index].changes" placeholder="请填写菜单名" v-model="menuData[scope.$index].dishname"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="unitprice" label="单价" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="menuData[scope.$index].changes">{{menuData[scope.$index].unitprice}}</span>
                <el-input v-if="!menuData[scope.$index].changes" placeholder="请填写单价" v-model="menuData[scope.$index].unitprice"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容" align="center">
            <template slot-scope="scope">
              <div class="modify_icon">
                <span v-if="menuData[scope.$index].changes">{{menuData[scope.$index].content}}</span>
                <el-input v-if="!menuData[scope.$index].changes" placeholder="请填写内容" v-model="menuData[scope.$index].content"></el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240" align="center">
            <template slot-scope="scope">
              <el-button @click="editInfo(scope.$index)" type="primary" size="mini">编辑</el-button>
              <el-button @click="deleteInfo(scope.$index,scope.row.id)" type="primary" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-form ref="form" style="text-align: center;" class="box" :model="intro" label-width="80px">
      <el-form-item>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveInfo(formline)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import E from "wangeditor";
  import $ from "jquery";
  import Qiniu from "../../../static/js/qiniu";
  import {
    setTimeout
  } from 'timers';
  export default {
    data() {
      return {
        editorContent: "", //富文本
        ImgData: [], //宴会厅图片
        bollroom: [], // 宴会厅数组
        menuData: [], //宴会菜单数组
        formline: {
          imagesData: [], //轮播图图片
          hotelname: "", //酒店名称
          price: "", //起订价
          contain: "", //容纳
          address: "", //地址
          dynamicTags: [] //标签
        },
        intro: {
          //酒店介绍
          desc: ""
        },
        inputVisible: false,
        inputValue: "",
        show: true,
        id: "",
        url: "",
        rules: {
          hotelname: [{
            required: true,
            message: '请输入酒店名称',
            trigger: 'blur'
          }],
          price: [{
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          }],
          contain: [{
            required: true,
            message: '请输入容纳人数',
            trigger: 'blur'
          }],
          address: [{
            required: true,
            message: '请输入酒店地址',
            trigger: 'blur'
          }],
          dynamicTags: [{
            required: true,
            message: '请输入标签',
            trigger: 'blur'
          }],
          imagesData: [{
            required: true,
            message: '请上传轮播图',
            trigger: 'blur'
          }]
        }
      };
    },
    created() {
      // 延迟执行，否则富文本不显示
      setTimeout(() => {
        this.wangeditor();
      }, 1000)
      let id = this.$route.query.infoId;
      this.id = this.$route.query.infoId;
      console.log(id);
      if (id) {
        //值不存在
        //值存在请求接口
        this.api
          .get("/api/hotel", {
            id: id
          })
          .then(res => {
            console.log(res.data);
            let info = res.data;
            this.formline.address = info.adress;
            this.formline.contain = info.accommodate;
            this.formline.dynamicTags = info.hotellable;
            this.formline.price = info.price;
            this.formline.hotelname = info.hotelname;
            this.formline.imagesData = info.images;
            this.bollroom = info.ballroom;
            this.editorContent = info.hoteldetial;
            // 宴会厅图片

            this.menuData = info.weddingmenu;
            console.log(this.menuData);
            for (let i = 0; i < this.menuData.length; i++) {
              this.$set(this.menuData[i], "num", i + 1);
              this.$set(this.menuData[i], "changes", true);
            }
            for (let i = 0; i < this.bollroom.length; i++) {
              this.$set(this.bollroom[i], "num", i + 1);
              this.$set(this.bollroom[i], "changes", true);
            }
          });
      }
    },
    methods: {
      cancel() {
        this.$router.go(-1)
      },
      // 富文本
      wangeditor() {
        var editor = new E("#editorElem");
        editor.customConfig.onchange = html => {
          this.editorContent = html;
        };
        editor.customConfig.qiniu = true;
        editor.customConfig.pasteFilterStyle = false;
        editor.create();
        editor.txt.html(this.editorContent);
        this.uploaderInit(editor);
      },
     blobToFile(dataurl, filename) { //base64位图片 转图片文件
       var arr = dataurl.split(','),
         mime = arr[0].match(/:(.*?);/)[1],
         bstr = atob(arr[1]),
         n = bstr.length,
         u8arr = new Uint8Array(n);
       while (n--) {
         u8arr[n] = bstr.charCodeAt(n);
       }
       return new File([u8arr], filename, {
         type: mime
       });
     },
     imgPreview(file, dataInfo) {
       let self = this
       // 判断是否支持FileReade
       if (!file || !window.FileReader) return
       // 创建一个reader
       var reader = new FileReader()
       // 将图片转成base64格式
       reader.readAsDataURL(file)
       // 读取成功后的回调
       reader.onloadend = function() {
         let result = this.result
         let img = new Image()
         img.src = result
         console.log('============未压缩图片===========')
         console.log(result.length)
         img.onload = function() {
           let data = self.compress(img)
           console.log(data.length)
           self.imgUrl = result
           var param = new FormData()
           let imgData = self.blobToFile(data, 'ig1')
           console.log(data)
           param.append('files', imgData)
           self.api.post('/api/imgs', param).then(res => {
             dataInfo.push(res.data[0])
           })
         }
       }
     },
     compress(img) {
       let canvas = document.createElement("canvas");
       let ctx = canvas.getContext("2d");
       let initSize = img.src.length;
       let width = img.width;
       let height = img.height;
       canvas.width = width;
       canvas.height = height;
       // 铺底色
       ctx.fillStyle = "#fff";
       ctx.fillRect(0, 0, canvas.width, canvas.height);
       ctx.drawImage(img, 0, 0, width, height);

       //进行最小压缩
       let ndata = canvas.toDataURL("image/jpeg", 0.1);
       console.log("*******压缩后的图片大小*******");
       // console.log(ndata)
       console.log(ndata.length);
       return ndata;
     },
     uploadImg(e) {
       let that = this;
       let formData = new FormData()
       let reader = new FileReader()
       let imgName = e.target.files[0]
       reader.readAsDataURL(e.target.files[0])
       that.imgPreview(imgName, that.formline.imagesData)
       // //上传图片
       // console.log(e);
       // let file = e.target.files[0];
       // let param = new FormData();
       // param.append("files", file, file.name);
       // let config = {
       //   headers: {
       //     "Content-Type": "multipart/form-data"
       //   }
       // };
       // this.api.post("/api/imgs", param, config).then(res => {
       //   this.formline.imagesData.push(res.data[0]);
       // });


     },
      bollroomImg(e, index) {
        //宴会厅上传图片
        console.log(index, "index");
        let file = e.target.files[0];
        let param = new FormData();
        param.append("files", file, file.name);
        console.log(param);
        let config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        };
        this.api.post("/api/imgs", param, config).then(res => {
          console.log(res.data[0], "address");
          this.$set(this.bollroom[index], "picture", res.data[0]);
        });
      },
      push_case() {
        //添加宴会厅
        let item = {
          num: this.bollroom.length + 1,
          name: "",
          height: "",
          floor: "",
          pillar: "",
          table: "",
          pricing: "",
          table: "",
          picture: "",
          changes: true
        };
        this.bollroom.push(item);
      },
      editor(index) {
        //编辑宴会厅
        this.bollroom[index].changes = !this.bollroom[index].changes;
      },
      push_Menu() {
        //添加宴会厅
        let item = {
          num: this.menuData.length + 1,
          dishname: "",
          unitprice: "",
          content: "",
          changes: true
        };
        this.menuData.push(item);
      },
      editInfo(index) {
        //编辑婚宴菜单
        console.log(index);
        this.menuData[index].changes = !this.menuData[index].changes;
      },
      editHotel(index) {
        //编辑宴会厅
        this.bollroom[index].changes = !this.bollroom[index].changes;
      },
      preserveHotel(index) {
        //保存
        this.bollroom[index].changes = true;
      },
      preserveMenu(index) {
        //保存
        this.menuData[index].changes = true;
      },
      saveInfo(formline) {
        this.$refs.formline.validate((valid) => {
          if (valid) {
             const _this = this;
            var param = {
              accommodate: _this.formline.contain,
              adress: _this.formline.address,
              hotelname: _this.formline.hotelname,
              hotellable: _this.formline.dynamicTags,
              price: _this.formline.price,
              images: _this.formline.imagesData,
              hoteldetial: _this.editorContent,
              weddingmenuDetial: _this.menuData,
              ballroomDetial: _this.bollroom
            };
            //提交数据
            if (_this.id) {
              console.log(param);
              _this.$set(param, 'id', _this.id);
              _this.api.post("/api/edithotel", param).then(res => {
                if (res.data) {
                  let info = res.data;
                  _this.formline.contain = info.accommodate;
                  _this.formline.address = info.adress;
                  _this.formline.hotelname = info.hotelname;
                  _this.formline.dynamicTags = JSON.parse(info.hotellable);
                  _this.formline.price = info.price;
                  _this.formline.imagesData = JSON.parse(info.images);
                  _this.editorContent = info.hoteldetial;
                  _this.menuData = JSON.parse(info.weddingmenu);
                  _this.bollroom = JSON.parse(info.ballroom);
                  _this.$message({
                    type: 'success',
                    message: '保存成功'
                  })
                  setTimeout(function() {
                    _this.$router.go(-1);
                  }, 2000);

                } else {
                  _this.$message.error(  '保存失败！')
                }
              });
            } else {
              _this.api.post("/api/edithotel", param).then(res => {
                if (res.data) {
                  let info = res.data;
                  _this.formline.contain = info.accommodate;
                  _this.formline.address = info.adress;
                  _this.formline.hotelname = info.hotelname;
                  _this.formline.dynamicTags = JSON.parse(info.hotellable);
                  _this.formline.price = info.price;
                  _this.formline.imagesData = JSON.parse(info.images);
                  _this.editorContent = info.hoteldetial;
                  _this.menuData = JSON.parse(info.weddingmenu);
                  _this.bollroom = JSON.parse(info.ballroom);
                  _this.$message({
                    type: 'success',
                    message: '保存成功'
                  })
                  setTimeout(function() {
                    _this.$router.go(-1);
                  }, 2000);

                } else {
                  _this.$message({
                    type: 'wearing',
                    message: '保存失败！'
                  })
                }
              })
            }

          }
        })

      },
      cancelBollroom(index, row) {
        //取消宴会厅
        console.log(index, row);
        this.index.splice(row, 1);
      },
      cancelMenu(index, row) {
        //取消宴会菜单
        this.menuData.splice(row, 1);
      },
      handleClose(index) {
        //删除标签
        this.formline.dynamicTags.splice(index, 1);
        if (this.dynamicTags.length != 3) {
          this.show = true;
        }
      },
      showInput() {
        //添加标签
        if (this.formline.dynamicTags.length >= 3) {
          this.show = false;
          alert("标签最多添加三个");
        } else {
          this.inputVisible = true;
          this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
          });
        }
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.formline.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = "";
      },
      deleteImg(index) {
        //删除图片
        this.formline.imagesData.splice(index, 1);
      },
      // 富文本
      uploaderInit(editor) {
        var that = this;
        var btnId = editor.imgMenuId;
        var containerId = editor.toolbarElemId;
        var textElemId = editor.textElemId;
        that.api.post("/api/uptoken", {}).then(res => {
          var uploader = new Qiniu().uploader({
            runtimes: "html5,flash,html4", //上传模式,依次退化
            browse_button: btnId, //上传选择的点选按钮，**必需**
            uptoken: res.data,
            unique_names: true,
            save_key: true,
            domain: "http://vrqn.liuliangin.com/", //bucket 域名，下载资源时用到，**必需**
            container: containerId, //上传区域DOM ID，默认是browser_button的父元素，
            max_file_size: "100mb", //最大文件体积限制
            filters: {
              mime_types: [
                //只允许上传图片文件 （注意，extensions中，逗号后面不要加空格）
                {
                  title: "图片文件",
                  extensions: "jpg,gif,png,bmp"
                }
              ]
            },
            max_retries: 3, //上传失败最大重试次数
            dragdrop: true, //开启可拖曳上传
            drop_element: textElemId, //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
            chunk_size: "4mb", //分块上传时，每片的体积
            auto_start: true, //选择文件后自动上传，若关闭需要自己绑定事件触发上传
            init: {
              FilesAdded: function(up, files) {
                plupload.each(files, function(file) {
                  // 文件添加进队列后,处理相关的事情
                  that.printLog("on FilesAdded");
                });
              },
              BeforeUpload: function(up, file) {
                // 每个文件上传前,处理相关的事情
                that.printLog("on BeforeUpload");
              },
              UploadProgress: function(up, file) {
                // 显示进度
                that.printLog("进度 " + file.percent);
              },
              FileUploaded: function(up, file, info) {
                // 每个文件上传成功后,处理相关的事情
                // 其中 info 是文件上传成功后，服务端返回的json，形式如
                // {
                //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //    "key": "gogopher.jpg"
                //  }
                that.printLog(info);
                // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
                var domain = up.getOption("domain");
                var res = $.parseJSON(info.response);
                var sourceLink = domain + res.key; //获取上传成功后的文件的Url
                that.printLog(sourceLink);
                // 插入图片到editor
                editor.cmd.do(
                  "insertHtml",
                  '<img src="' + sourceLink + '" style="max-width:100%;"/>'
                );
              },
              Error: function(up, err, errTip) {
                //上传出错时,处理相关的事情
                that.printLog("on Error");
              },
              UploadComplete: function() {
                //队列文件处理完毕后,处理相关的事情
                that.printLog("on UploadComplete");
              }
            }
            //upload的括号
          });
        });
      },
      printLog(title, info) {
        console.log(title, "1");
        console.log(info, "2");
        window.console && console.log(title, info);
      }
      // 富文本结束

    }
  };
</script>

<style scoped>
  .box {
    width: 50%;
  }

  .file {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 35px;
    line-height: 35px;
    text-align: center;
    opacity: 0;
  }

  .el-button {
    width: 100px;
  }

  .loade_img {
    background: url("./../../../static/img/push.jpg") no-repeat;
    background-size: 80px 80px;
    width: 80px;
    height: 80px;
  }

  .loade_img div {
    margin: 10px 5px 5px;
    width: 80px;
    height: 80px;
    float: left;
  }

  .loade_img img {
    width: 80px;
  }

  .topimg .banner_loade {
    display: inline-block;
    flex-direction: none;
    align-content: initial;
    justify-content: none;
  }

  .hide {
    width: 100%;
    background-image: none;
  }

  .icon {
    font-size: 25px;
    position: absolute;
    top: -8px;
    right: -8px;
  }

  .upload {
    position: relative;
    width: 120px;
    height: 35px;
  }

  .banner {
    font-size: 20px;
  }

  .push-banner {
    display: inline-block;
    margin-left: 43px;
  }

  .push-banner>i {
    font-size: 30px;
    vertical-align: middle;
    cursor: pointer;
  }

  .push-banner>span {
    color: #999;
    margin-left: 37px;
  }

  .item-table {
    width: 100%;
    margin: 4% 0;
  }

  .banner_loade {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .img_auto {
    max-width: 100%;
    width: 100%;
    max-height: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>
